from PIL import Image

def calculate_ahash(image_path):
    """
    计算给定图片的aHash（均值哈希）值。

    Args:
        image_path (str): 图片文件的路径。

    Returns:
        str: 图片的64位二进制aHash字符串。
    """
    # 1. 灰度化并缩小图片到8x8像素
    img = Image.open(image_path).convert("L").resize((8, 8), Image.Resampling.LANCZOS)
    
    # 2. 计算这64个像素的平均灰度值
    pixels = list(img.getdata())
    avg_pixel_value = sum(pixels) / len(pixels)
    
    # 3. 生成哈希指纹
    # 遍历每个像素，如果大于或等于均值则为1，否则为0
    ahash_bits = []
    for pixel in pixels:
        if pixel >= avg_pixel_value:
            ahash_bits.append("1")
        else:
            ahash_bits.append("0")
            
    return "".join(ahash_bits)

def hamming_distance(hash1, hash2):
    """
    计算两个哈希字符串之间的汉明距离。
    汉明距离越小，表示两个哈希越相似。
    """
    if len(hash1) != len(hash2):
        raise ValueError("哈希字符串长度不一致")
    
    distance = 0
    for i in range(len(hash1)):
        if hash1[i] != hash2[i]:
            distance += 1
            
    return distance


if __name__ == "__main__":
    original_image_path = './Image_deduplication/original_image.jpg'
    different_image_path = './Image_deduplication/different.jpg'

    try:
        # 打开原始图片
        original_img = Image.open(original_image_path)

        # 生成缩放版本
        resized_img = original_img.resize((original_img.width // 2, original_img.height // 2))
        resized_img_path = './Image_deduplication/resized_image.jpg'
        resized_img.save(resized_img_path)

        # 生成亮度调整版本
        bright_img = original_img.point(lambda p: p * 1.5)
        bright_img_path = './Image_deduplication/brightened_image.jpg'
        bright_img.save(bright_img_path)

        image_paths = [original_image_path, resized_img_path, bright_img_path, different_image_path]

        print("--- 计算 aHash 值 ---")
        hashes = []
        for path in image_paths:
            img_hash = calculate_ahash(path)
            hashes.append(img_hash)
            print(f"{path} aHash: {img_hash}")

        print("\n--- 计算汉明距离 ---")
        original_hash = hashes[0]
        for i in range(1, len(hashes)):
            print(f"Original vs {image_paths[i]} Distance: {hamming_distance(original_hash, hashes[i])}")

    except FileNotFoundError as e:
        print(f"错误：图片文件未找到。请检查 'original_image.png' 和 'different.png' 是否存在于当前目录下。")
        print(f"具体错误：{e}")
    except Exception as e:
        print(f"发生了一个错误：{e}")